import Vue from 'vue'
// v-draggable: 用于监听拖动事件，计算拖动的距离并更新元素的宽度
Vue.directive('draggable', {
	bind (el, binding, vnode, oldVnode) {
		// 获取外部传入的值
		const draggableOptions = binding.value
		const minWidth = draggableOptions.minWidth || 100
		let maxWidth = draggableOptions.maxWidth || 400
		// 添加一个全局的事件监听器来监听maxWidth的变化
    vnode.context.$watch('maxWidth', (newMaxWidth) => {
      // 当maxWidth变化时，手动更新宽度约束
      maxWidth = newMaxWidth
    })
		const resizableLine = el.querySelector('.resizableLine')
		let startX, startWidth
		resizableLine.addEventListener('mousedown', function (event) {
			event.preventDefault() // 添加这行代码阻止默认文本选取行为
			startX = event.clientX
			startWidth = parseInt(getComputedStyle(el).width, 10)
			document.addEventListener('mousemove', onMousemove)
			document.addEventListener('mouseup', onMouseup)
			function onMousemove(event) {
				const newWidth = startWidth + event.clientX - startX
				// 应用minWidth和maxWidth约束
				const resWidth = Math.min(Math.max(newWidth, minWidth), maxWidth)
				el.style.width = `${resWidth}px`
				draggableOptions.handler && draggableOptions.handler(resWidth)
			}
			function onMouseup() {
				document.removeEventListener('mousemove', onMousemove)
				document.removeEventListener('mouseup', onMouseup)
			}
		})
	}
})

// v-resize监听元素的尺寸变化
Vue.directive('resize', {
	bind(el, binding, vnode) {
		const vm = vnode.context // 获取Vue实例
		const handler = binding.value
		const ro = new ResizeObserver(entries => {
			for (const entry of entries) {
				handler(entry.contentRect.width, entry.contentRect.height)
			}
		})
		vm.$nextTick(() => {
      ro.observe(el)
    });
    vm.ro = ro // 将ResizeObserver实例附加到Vue实例上
	},
	unbind(el, binding, vnode) {
		const vm = vnode.context
		if (vm.ro) {
      vm.ro.unobserve(el)
      vm.ro.disconnect()
      delete vm.ro // 移除Vue实例上的ro属性
    }
	},
})
